package cn.lu.joke.util;

import android.app.Activity;
import android.support.v4.util.ArrayMap;

import java.lang.ref.WeakReference;
import java.util.Map;

public class ActivityManager {
    private ActivityManager() {
        mActivityMap = new ArrayMap<>();
    }

    private Map<Class, WeakReference<Activity>> mActivityMap;

    public static ActivityManager get() {
        return Holder.INSTANCE;
    }

    public <T extends Activity> T getActivity(Class<T> cls) {
        if (mActivityMap.get(cls) != null) {
            return (T) mActivityMap.get(cls).get();
        }
        return null;
    }

    public void put(Activity activity) {
        mActivityMap.put(activity.getClass(), new WeakReference<>(activity));
    }

    public void remove(Class cls) {
        if (mActivityMap.containsKey(cls)) {
            mActivityMap.remove(cls);
        }
    }

    public void finishActivity(Class cls) {
        WeakReference<Activity> ref = mActivityMap.get(cls);
        if (ref == null) {
            return;
        }
        remove(cls);
        Activity ay = ref.get();
        if (ay != null) {
            ay.finish();
        }
    }

    private static class Holder {
        private static final ActivityManager INSTANCE = new ActivityManager();
    }

}
